/**
 * @author Sunny xing
 */
(function(){
    Simple.namespace("keyCode");
    Simple.mixin(Simple.keyCode, {
        ENTER: function(e){
            return e.keyCode == 13;
        },
        ESC: function(e){
            return e.keyCode == 27;
        },
        DOWN: function(e){
            return e.keyCode == 40;
        },
        UP: function(e){
            return e.keyCode == 38 ;
        },
        PAGE_LEFT: function(e){
        
        },
        PAGE_RIGHT: function(e){
        
        },
        SHIFT: function(e){
            return e.keyCode == 16;
        },
        CTRL: function(e){
            return e.keyCode == 17;
        },
        ALT: function(e){
            return e.keyCode == 18;
        },
        BACKSPACE: function(e){
            return e.keyCode == 8;
        }
    });
   Simple.declare("AutoComplete", null,{
        //触发自动完成的节点
        node: null,
        //获取内容渲染的位置
        renderTo: null,
        //数据源,array,json
        //["javascript","java","jsscript","actionscript"]
        //[]
        source: null,
        format: null,
		width:null,
        init: function(){
            var self = this;
            this.node = $(this.node);
            this.render = $(this.renderTo);
			if(this.width){
				this.render.width(this.width)
			}else{
				this.render.width(this.node.width());
			}
            this.node.bind("autocomplete/keyupEvent", function(e, event){
                self._keyupEvent.apply(self, [event]);
            }).bind("autocomplete/blurEvent", function(){
                self._blurEvent.apply(self);
            }).attr("autocomplete", "off");
            this.node.keydown(function(e){
                self.node.trigger("autocomplete/keyupEvent", [e]);
            });
            this.node.blur(function(e){
                self.node.trigger("autocomplete/blurEvent");
            });
            this.firstKeyDown = true;
        },
        destroy: function(){
            this.node.unbind("autocomplete/keydownEvent").unbind("autocomplete/blurEvent").removeAttr("autocomplete");
        },
        _keyupEvent: function(e){
            var val = $.trim(this.node.val()), name = this.node.attr("name"), selector, pos,self=this;
			if(val.length<1){
				this.render.hide();
				return;
			}
            if (Simple.keyCode.UP(e) || Simple.keyCode.DOWN(e)) {
                if (this.MenuContainer) {
                    var length = this.MenuContainer.children().length;
                    if (Simple.keyCode.DOWN(e)) {
                        selector = "eq(0)";
                        pos = "next"
                    }
                    else 
                        if (Simple.keyCode.UP(e)) {
                            selector = "last";
                            pos = "prev"
                        }
                    if (this.firstKeyDown) {
                        this.MenuContainer.find("li:" + selector).addClass("Y-autoComplete-selected");
                        this.firstKeyDown = false;
                    }
                    else {
                        var nextSelect;
                        if ($(".Y-autoComplete-selected").attr('data-index') == length - 1 && Simple.keyCode.DOWN(e)) {
                            nextSelect = this.MenuContainer.find("li:eq(0)");
                        }
                        else 
                            if ($(".Y-autoComplete-selected").attr('data-index') == 0 && Simple.keyCode.UP(e)) {
                                nextSelect = this.MenuContainer.find("li:last");
                            }
                            else {
								var selected=this.MenuContainer.find(".Y-autoComplete-selected").removeClass("Y-autoComplete-selected");
                                nextSelect = selected[pos]();
                            }
						this.MenuContainer.find(".Y-autoComplete-selected").removeClass("Y-autoComplete-selected");
                        nextSelect.addClass("Y-autoComplete-selected");
                    }
                    this.node.val(this.MenuContainer.find(".Y-autoComplete-selected").attr("data-val"));
                }
            }
            else {
                if (typeof this.source == "string") {
					var data={};
					data[name]=val;
                    $.ajax({
                        url: this.source,
                        data: data,
                        success: function(result){
							result=eval("("+result+")");
                            if (result.length > 0) {
                                self._createMenu(result,val);
                            }
                            else {
                                self.render.hide();
                            }
                        }
                    });
                }
                else 
                    if (this.source instanceof Array) {
                        var newArr = [];
                        $.each(this.source, function(i, n){
							var reg=new RegExp(val,"gi");
                            if (reg.test(n)) {
                                newArr.push(n);
                            }
                        });
                        if (newArr.length > 0) {
                            this._createMenu(newArr,val);
                        }
                        else {
                            this.render.hide();
                        }
                    }
                this.firstKeyDown = true;
            }
        },
        _blurEvent: function(){
			//editor by sky
			//node 节点失去焦点时 隐藏下拉选项  -------  增加了一个状态变量
			if(!this._mouseInSelect){
				this.render.hide();
			}
        },
        _createMenu: function(data,key){
            var self = this;
            var ul = $("<ul>").addClass("Y-autocomplete-menu");
            this.MenuContainer = ul;
            $.each(data, function(i, n){
                self._formatData(n, i,key);
            });
            this.render.empty().append(this.MenuContainer).slideDown("fast");
        },
        _formatData: function(item,index,key){
            var li,self=this;
            if (typeof this.format == "function") {
                li = this.format(item,index,key);
				li.attr({
					"data-val":item,
					"data-index":index
				});
            }
            else {
				li = $("<li/>").attr("data-val", item)
				item=item.replace(key,"<b class='orange'>"+key+"</b>");
                li.html(item).attr('data-index', index);
            }
			
			//editor by sky
			//1. 鼠标点击选项时候隐藏列表！
			//2. node 节点失去焦点时 隐藏下拉选项  -------  增加了一个状态变量
			li.mouseover(function(){
				$(this).addClass("Y-autoComplete-selected").siblings().removeClass("Y-autoComplete-selected");
				self._mouseInSelect = true; 
			}).mouseout(function(){
				self._mouseInSelect = false;
			}).click(function(){
				self.node.val($(this).attr('data-val'));
				self._mouseInSelect = false;
				self.render.hide();
			})
			//.keydown(function(e){
				//self._keydownEvent.apply(self,[e]);
			//});
            this.MenuContainer.append(li);
        }
    });
    
    Simple.bridgeTojQuery("autocomplete",Simple.AutoComplete);
})();
